<template>
  <span style="position: absolute;font-size: 18px;top: 17px;left:14px;font-weight: lighter;" @click="my">我的</span>
<!--        @search="onSearch"-->
<!--  @input = "console.log(123)"-->
  <van-search
      v-model="value"
      show-action
      placeholder="请输入搜索关键词"
      @update:model-value = "getUl()"
      style="margin-left:50px;"
  > </van-search>
<!--  @search="onSearch"
      @cancel="onCancel"-->
<!--  <searchResult v-if="showUl" />-->
<!--  &lt;!&ndash; 搜索结果 &ndash;&gt;-->
<!--  &lt;!&ndash; 联想建议 &ndash;&gt;-->
<!--  <searchSuggestion v-else-if="value" />-->

  <ul v-if="showUl" style="margin-left: 70px;">
    <li v-for="item in UlList" :key="item.id" style="font-family: SongTi;font-size: 16px; margin-top: 5px" @click="onSearch(item)">{{item.address}}</li>
  </ul>
  <baidu-map class="bm-view"  :scroll-wheel-zoom="true"  :center="mapCenter" :zoom="15">
<!--    <BMarker v-for="site in SiteList" :title="site.address" :position="{ lng: site.x, lat: site.y }"-->
<!--             @click="openPopover(site)"/>-->
    <bm-navigation anchor="BMAP_ANCHOR_TOP_RIGHT"></bm-navigation>
    <bm-geolocation @locationSuccess="locationSuccess" anchor="BMAP_ANCHOR_BOTTOM_RIGHT" :showAddressBar="true" :autoLocation="true"></bm-geolocation>
    <bm-marker v-for="site in SiteList"  @click="openPopover(site)" :title="site.address" :position="{ lng: site.x, lat: site.y }" animation="BMAP_ANIMATION_BOUNCE">
    </bm-marker>
    <bm-driving v-if="flag2" :start="lushuPoint.start" :end="lushuPoint.end" :auto-viewport="true" policy="BMAP_DRIVING_POLICY_LEAST_DISTANCE">
    </bm-driving>
  </baidu-map>
  <div class="test" style="position: absolute;top: 776px;left: 0px;">
    <div
        style="width:430px;height:160px;background-color: white;border-radius: 100% 100% 0 0;box-shadow: 0px -1px 10px silver;">


      <div v-if="isUse" style="position: absolute;top: 80px;left:30px;font-size: 12px">
        <img src="../assets/images/图标.png" style="width: 90px; height: 90px;margin-top: -40px;margin-left: 20px">
      </div>
      <div v-if="isUse" style="position: absolute;top: 80px;left:300px;font-size: 12px">
        <img src="../assets/images/电池.png" style="width: 90px; height: 90px;margin-top: -40px;margin-left: -20px">
      </div>
      <div :style="css" @click="saoma" ref="data">

        <img
          :src="tubiao" style="width:55px;height:55px;margin-top:16px;margin-left:22.5px;" @click="open"/>

        <span style="font-size: 13px;display: block;margin-left: 25px;margin-top: -6px;color: white;">扫码换电</span>
      </div>

    </div>
  </div>
<!--  <van-dialog v-model:show="showPopover" title="标题" :confirm="shoucang()">-->
<!--&lt;!&ndash;    12312312&ndash;&gt;-->
<!--  </van-dialog>-->
  <el-dialog v-model="dialogFormVisible" title="站点详情" width="430">
    站点名称:{{showSite.address}}<br/>
    站点电柜数量:{{showSite.cabinetNum}}<br/>
    低压电池数量:{{showSite.minBattery}}<br/>
    高压电池数量:{{showSite.maxBattery}}<br/>
    电池数量:{{showSite.minBattery+showSite.maxBattery}}<br/>
    站点图片:
    <el-image :src="showSite.image"/>
    <template #footer>
        <el-button @click="dialogFormVisible = false">关闭</el-button>
        <el-button type="primary" @click="collect()">
          收藏
        </el-button>
      <el-button type="primary" @click="openYu()">
          预约电池
      </el-button>
      <el-button type="primary" @click="toAddress()">
          导航到此处
      </el-button>
    </template>
  </el-dialog>
  <el-dialog
      v-model="dialogVisible"
      title="预约电池"
      width="430"
  >
    低压电池可用数量:{{showSite.minBattery}}<br/>
    高压电池可用数量:{{showSite.maxBattery}}<br/>
    当前位置:{{showYu.nowAddress}}<br/>
    距离目标站点:{{showYu.distance}}m<br/>
    请选择电池类型:
    <el-radio-group v-model="reservation.btid" size="small">
      <el-radio-button v-for="item in batteryType" :key="item.id" :label="item.batteryType" :value="item.id" @change="getBattery(item.id)"/>
    </el-radio-group>
    <br/>
    <span v-if="flag">选择电池品牌</span>
    <br/>
    <el-select
        v-model="reservation.bid"
        placeholder="请选择电池品牌"
        size="large"
        style="width: 240px"
        v-if="flag"
    >
      <el-option v-for="item in BatteryList" :key="item.id" :label="item.batteryName" :value="item.id"/>
    </el-select>
    <template #footer>
      <div class="dialog-footer">
        <el-button @click="dialogVisible = false">关闭</el-button>
        <el-button type="primary" @click="addReservation()">
          申请预约
        </el-button>
      </div>
    </template>
  </el-dialog>



<!--  -->

  <el-dialog
      v-model="dialogTimeVisible"
      title="预约成功"
      width="430"
  >
    <span>当前剩余{{exportTime}}分钟，请尽快前往{{showSite.address}}换电</span>
    <template #footer>
      <div class="dialog-footer">
        <el-button @click="dialogTimeVisible = false">关闭</el-button>
      </div>
    </template>
  </el-dialog>


<!--  登录的用户校验-->
  <van-toast v-model:show="show" style="padding: 10px" position="top" duration="toast" :closeOnClick="true">
    <template #message>
      <span>你尚未登录，暂时无法租借</span>&nbsp;<van-button type="info" size="small" style="color:black" @click="loginVue()">登录</van-button>
    </template>
  </van-toast>
  <van-toast v-model:show="show1" style="padding: 10px" position="top" duration="toast" :closeOnClick="true">
    <template #message>
      <span>你尚未实名认证，暂时无法租借</span>&nbsp;<van-button type="info" size="small" style="color:black" @click="renzheng()">认证</van-button>
    </template>
  </van-toast>
  <van-toast v-model:show="show2" style="padding: 10px" position="top" duration="toast" :closeOnClick="true">
    <template #message>
      <span>你尚未购买套餐，请购买之后使用</span>&nbsp;<van-button type="info" size="small" style="color:black" @click="taocan">购买</van-button>
    </template>
  </van-toast>
</template>
<script setup>
import tubiao from "@/assets/images/tubiao.png";
import {getSite, getSiteListByRedis} from "@/api/site.js";
import { getCabinetInfo } from "@/api/cabinet.js"
import {CollectSite} from "@/api/UserSite.js";
import {ElMessage} from "element-plus";
import {MessageBox} from "@element-plus/icons-vue";
import { Camera } from '@element-plus/icons-vue';
import {userData} from "@/api/userinfo.js";
import { showToast } from 'vant';
import {getAddressXY, getDistance} from "@/api/Map.js";
import {getBatteryTypeList} from "@/api/BattertType.js";
import {getBatteryList} from "@/api/Battert.js";
import {ReservationTime, saveReservation} from "@/api/reservation.js";
import {useRouter} from "vue-router";
const address = ref('');
const MapVo = ref({
  objectX:0,
  objectY:0,
  nowX:0,
  nowY:0,
  nowAddress:'',
})
  const locationSuccess=  (e) => {
    // 定位成功事件
    address.value = ''
    address.value += e.addressComponent.province;
    address.value += e.addressComponent.city;
    address.value += e.addressComponent.district;
    address.value += e.addressComponent.street;
    MapVo.value.nowAddress = address.value;
    getAddressXY(address.value).then(res=>{
      if (res.data.code===200){
        console.log(res.data.data)
        MapVo.value.nowX = res.data.data.nowX;
        MapVo.value.nowY = res.data.data.nowY;
      }
    })
}



//获取所有的站点信息
const SiteList = ref([]);
const getSiteList = async () => {
  const {data} = await getSite()
  if (data.code === 200) {
    SiteList.value = data.data
  }
}
const dialogFormVisible = ref(false);
const showSite = ref({
  address:'',
  cabinetNum:0,
  minBattery:0,
  maxBattery:0,
  image:'',
  sid:0,
})
const openPopover = async (site) => {
  // showPopover.value = true;
  dialogFormVisible.value=true;
  MapVo.value.objectX=site.x;
  MapVo.value.objectY=site.y;
  showSite.value.address=site.address;
  showSite.value.image = site.image;
  showSite.value.sid=site.id;
  reservation.value.sid=site.id
  //通过sid获取电池柜信息
  const {data} =await getCabinetInfo(site.id)
  if (data.code===200){
    showSite.value.cabinetNum=data.data.length;
    showSite.value.minBattery=0;
    showSite.value.maxBattery=0;
    console.log(data.data)
    for (let dataKey in data.data) {
      showSite.value.minBattery+=data.data[dataKey].minBattery;
      showSite.value.maxBattery+=data.data[dataKey].maxBattery;
    }
  }
};
onMounted(() => {
  getSiteList()
  getBatteryType()
  getUser()
})
const collect = async () =>{
  const { data } = await CollectSite(showSite.value.sid)
  if(data.code===200){
    ElMessage.success(data.message)
    dialogFormVisible.value=false;
  }else {
    ElMessage.error(data.message)
    dialogFormVisible.value=false;
  }
}
//
const dialogVisible = ref(false)
const showYu = ref({
  distance:0,
  nowAddress:'',
})
const openYu = async () =>{
  reservation.value.btid=0
  reservation.value.bid=0
  flag.value = false
  if (!MapVo.value.nowAddress){
    ElMessage.error('请先定位')
    dialogVisible.value=false
    dialogFormVisible.value=false
    return
  }
  dialogVisible.value=true;
  const {data} = await getDistance(MapVo.value)
  if (data.code===200){
    showYu.value.distance=data.data.distance;
    showYu.value.nowAddress=data.data.nowAddress;
  }
}
//
const reservation = ref({
  sid:0,
  bid:0,
  btid:0,
})
//获取电池类型
const batteryType = ref([])
const getBatteryType = async () =>{
  const {data}=await getBatteryTypeList();
  if (data.code===200){
    batteryType.value=data.data
  }
}
const flag = ref(false)
const BatteryList = ref([])
const getBattery = async (byid) =>{
  reservation.value.bid=null
  reservation.value.btid = byid
  const {data} = await getBatteryList(byid)
  if (data.code===200){
    flag.value = true
    BatteryList.value = data.data
  }
}
//添加预约信息
const addReservation = async () =>{
  const {data} = await saveReservation(reservation.value)
  if (data.code===200){
    ElMessage.success(data.message)
    dialogVisible.value=false
    dialogFormVisible.value=false
    localStorage.setItem("reservation",data.data)
  }else {
    dialogVisible.value=false
    dialogFormVisible.value=false
    ElMessage.error(data.message)
  }
}
const rTime = ref(localStorage.getItem("reservation")??null)
const dialogTimeVisible = ref(false)
const exportTime=ref(0)
setInterval(()=>{
  getReservationTime()
},300000)
const getReservationTime = async ()=>{
  if (rTime.value!=null){
    const {data} = await ReservationTime(rTime.value)
    if (data.data!=null){
    dialogTimeVisible.value=true;
    exportTime.value=data.data
    }else {
      localStorage.removeItem('reservation')
      ElMessage.error('预约信息已过期')
    }
  }
}
const getUser=async ()=>{
  const {data} =await userData();
  if(data.code===200){
    if(data.data.status===0){
      show1.value=true;
    }else if(data.data.status===1){
      if(data.data.planStatus===0){
        show2.value=true;
      }
    }
  }else{
    show.value=true;
  }
}
let show=ref(false);
let show1=ref(false);
let show2=ref(false);
const router=useRouter();
const loginVue=()=>{
  router.replace({name:'login'})
}
const renzheng=()=>{
  if(show.value===false) {
    router.replace({name: "authentication"})
  }else{
    ElMessage.error('请先登录')
  }
}
const saoma=()=>{
  if(show1.value==false&&show.value==false) {
    router.replace({name: "usercontroll"})
  }else if(show.value==true){
    ElMessage.error('请先登录')
  }else{
    ElMessage.error('请先认证')
  }
}
// 套餐
const taocan=()=>{
  if(show.value===false) {
    router.replace({name: "packagee"})
  }else{
    ElMessage.error('请先登录')
  }
}
const my=()=>{
  router.replace({name:"userinfo"})
}
//导航路线
const flag2 = ref(false)
const lushuPoint = ref({
  start: {
    lng: 116.301934,
    lat: 39.977552
  },
  end: {
    lng: 116.508328,
    lat: 39.919141
  },
});
const toAddress = () =>{

  if (MapVo.value.nowX !=0 && MapVo.value.nowY !=0 ){
    flag2.value = true
    lushuPoint.value.start.lat = MapVo.value.nowY
    lushuPoint.value.start.lng = MapVo.value.nowX
    lushuPoint.value.end.lat = MapVo.value.objectY
    lushuPoint.value.end.lng = MapVo.value.objectX
    dialogFormVisible.value=false;
  }else {
    dialogFormVisible.value=false;
    ElMessage.error('请先定位')
  }
}


//
const mapCenter = ref({
    lng: 115.491402,
    lat: 38.821023
})
const showUl = ref(false)
const UlList = ref([])
const value = ref('');
const  getUl = async () =>{
  const {data} = await getSiteListByRedis(value.value)
  if (value.value !== '' && value.value !=null){
    showUl.value = true
    UlList.value = data.data
  }else {
    showUl.value = false
  }
}

const onSearch = (row) =>{
  mapCenter.value.lat =row.y
  mapCenter.value.lng =row.x
  value.value = ""
  showUl.value = false
}
var c=localStorage.getItem('isUse');
const isUse = ref(localStorage.getItem('isUse')??false)
const css=ref("width:100px;height:100px;border-radius: 100%;background-color: orange;margin-left: 165px;position: absolute;top: -40px")
console.log(isUse.value)
if(isUse.value){
  css.value="width:100px;height:100px;border-radius: 100%;background-color: orange;margin-left: 165px;position: absolute;top: -40px"
}else{
  css.value="width:100px;height:100px;border-radius: 100%;background-color: orange;margin-left: 165px;position: absolute;top: 20px"
}
</script>
<style>
.bm-view {
  width: 380px;
  height: 660px;
}
</style>